package com.xzt.meeting.controller;

import com.xzt.meeting.entity.Dept;
import com.xzt.meeting.entity.PageEntity;
import com.xzt.meeting.entity.User;
import com.xzt.meeting.service.DeptService;
import com.xzt.meeting.service.UserService;
import com.xzt.meeting.utils.FileUploadUtils;
import com.xzt.meeting.utils.MeetingUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

/**
 * @Author xzt
 * @Date 2022/5/7 8:19
 * @Version 1.0
 * @Introduce
 */
@WebServlet("/user/*")
public class UserServlet extends BaseServlet{

    private UserService userService = new UserService();

    private DeptService deptService = new DeptService();

    public void checkUsername(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        String username = req.getParameter("username");

        User user = userService.getUserByname(username);

        if (user == null){
            writerObjToString(resp,"0");
            return;
        }
        writerObjToString(resp,"1");
    }

    public void checkEmail(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        String email = req.getParameter("email");

        User user = userService.getUserByemail(email);

        if (user == null){
            writerObjToString(resp,"0");
            return;
        }
        writerObjToString(resp,"1");
    }

    public void login(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        String safeCode = (String) req.getSession().getAttribute("sessionCode");

        Map<String,String> param = getParam(req);
        String username = param.get("username");
        String password = param.get("password");
        String checkCode = param.get("checkCode");
        String remember = param.get("remember");

        System.out.println(username+"--"+password);

        User user = userService.getUserByname(username);

        if (!safeCode.equals(checkCode)){
            req.setAttribute("msg","验证码错误！");
            req.getRequestDispatcher(req.getContextPath() + "/index.jsp").forward(req,resp);
            return;
        }
        if(user == null){
            req.setAttribute("msg","用户名不存在，请注册！");
            req.getRequestDispatcher(req.getContextPath() + "/index.jsp").forward(req,resp);
            return;
        }
        if (!user.getPassword().equals(password)){
            req.setAttribute("msg","密码错误！");
            req.getRequestDispatcher(req.getContextPath() + "/index.jsp").forward(req,resp);
            return;
        }
        if ("1".equals(remember)) {

            // 说明用户勾选了 '记住我'
            Cookie cookie = new Cookie("loginUser", user.getId()+"");

            cookie.setPath("/");

            // cookie过期时间
            cookie.setMaxAge(60*60*24*7);

            // 写回客户端
            resp.addCookie(cookie);

        }
        // 更改用户登录时间
        userService.updateLoginTime(user.getId());

        req.getSession().setAttribute("loginUser",user);

        resp.sendRedirect("/html/home.jsp");
    }

    public void register(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        User user = new User();
        Map<String,String> param = getParam(req);
        try{
            BeanUtils.populate(user,param);
            userService.addUser(user);
            resp.sendRedirect("/index.jsp");
        }catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void findAll(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{

        Map<String,String> param = getParam(req);

        String realName = param.get("realName");

//        List<User> userList = userService.findAll();
        List<User> userList = userService.search(realName);
        req.setAttribute("userList",userList);
        req.setAttribute("realName",realName);
        req.getRequestDispatcher(req.getContextPath() + "/html/user.jsp").forward(req,resp);
    }

    public void findPage(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{

        Map<String, String> param = getParam(req);

        String realName = param.get("realName");

        // 当前页码
        Integer currPage = Integer.parseInt(param.get("currPage"));

        // 查询分页信息
        PageEntity<User> pageData = userService.findPage(realName, currPage);

        // 我关注的人列表(用于判断哪些是我关注的)
        List<Long> focusList = userService.findFocusListByUserId(loginUser.getId());

        req.setAttribute("focusList", focusList);

        // 分页信息
        req.setAttribute("pageData", pageData);
        // 前端回显
        req.setAttribute("realName", realName);

        req.getRequestDispatcher("/html/user.jsp").forward(req, resp);
    }

    public void userDetail(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        Map<String, String> param = getParam(req);

        Long id = Long.parseLong(param.get("id"));


        String flag = param.get("flag");

        User user = userService.findUserById(id);

        // 填充user信息
        req.setAttribute("user", user);

        if ("detail".equals(param.get("flag"))) {

            // 代表是查看别人的

            // 查看数+1
            userService.incLook(id);

            // 查询粉丝数
            Integer fansCount = userService.countFansByUserId(id);
            req.setAttribute("fans", fansCount);

            req.getRequestDispatcher("/html/user_detail.jsp").forward(req, resp);
            return;
        }
//        System.out.println(user);

        // 代表是查看自己的
        Integer focusCount = userService.countFocusByUserId(id);

        List<Dept> deptList = deptService.findAll();

        req.setAttribute("focus", focusCount);
        req.setAttribute("deptList", deptList);

        req.getRequestDispatcher("/html/user_look.jsp").forward(req, resp);
    }

    public void updatePic(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        // 调用文件上传工具类
        String fileName = FileUploadUtils.upload("/upload", req);

        // 上传到服务器端的真实路径
        String picUrl = "http://192.168.31.21:8080/upload/" + fileName;

        // 修改session中的pic地址
        loginUser.setPic(picUrl);
        session.setAttribute("loginUser",loginUser);

        // 修改数据库中的pic地址
        userService.updateUrl(loginUser.getId(), picUrl);

        // 将新的图片地址写到前端
        writerObjToString(resp, picUrl);
    }

    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        BeanUtils.populate(user, getParam(req));

        User dbUser = userService.findUserById(user.getId());

        // 查询部门信息
        Dept dept = deptService.findById(user.getDeptId());

        // 设置前端不能提交的参数
        user.setPic(dbUser.getPic());
        user.setLook(dbUser.getLook());
        user.setPassword(dbUser.getPassword());
        user.setEmail(dbUser.getEmail());
        // 部门名称
        user.setDeptName(dept.getName());

        // 前端没有勾选默认为公开
        if (user.getIsSecret() == null) {
            user.setIsSecret("1");
        }

        userService.update(user);

        // 重新放入session
        session.setAttribute("loginUser", user);

        // 重新重定向到userDetail请求填充数据,然后通过userDetail转发到对应的页面进行数据渲染
        resp.sendRedirect("/user/userDetail?flag=detail&id=" + dbUser.getId());
    }

    public void focus(HttpServletRequest req,HttpServletResponse resp){
        Map<String, String> param = getParam(req);

        Long userid = Long.parseLong(param.get("userId"));

        // 用户加关注(1:关注  0:取消关注)
        Integer flag = userService.focus(loginUser.getId(),userid);

        writerObjToString(resp,flag);
    }

    public void findFocusPage(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String> param = getParam(req);

        // 当前页码
        Integer currPage = Integer.parseInt(param.get("currPage"));

        PageEntity<Map<String,Object>> pageEntity = userService.findFocusPage(loginUser.getId(),currPage);
        req.setAttribute("pageData",pageEntity);
        req.getRequestDispatcher(req.getContextPath() + "/html/my_user.jsp").forward(req,resp);
    }

    public void findUserByDeptId(HttpServletRequest req,HttpServletResponse resp){
        Map<String, String> param = getParam(req);

        Long deptId = Long.parseLong(param.get("deptId"));

        List<Map<String,Object>> list = userService.findUserByDeptId(deptId);

        writerObjToString(resp,list);
    }

    public void logout(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        // 清除session
        req.getSession().removeAttribute("loginUser");

        Cookie loginCookie = MeetingUtils.getCookie(req, "loginUser");

        if (loginCookie != null) {

            // 销毁cookie
            loginCookie.setPath("/");
            loginCookie.setMaxAge(0);
            resp.addCookie(loginCookie);
        }

        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    }

    //修改密码的模拟向邮箱发送验证码
    public void sendCode(HttpServletRequest req,HttpServletResponse resp){
        String email = getParam(req).get("email");
        User user = userService.getUserByemail(email);
        if (user == null){
            writerObjToString(resp,"0");
        }else {
            Random random = new Random();
            String str = Integer.toHexString(random.nextInt());

            String code = str.substring(0,4);

            HttpSession session = req.getSession();

            session.setAttribute("forgetCode",code);

            writerObjToString(resp,code);
        }
    }

    //修改密码
    public void forgetPassword(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        String email = getParam(req).get("email");
        String checkCode = getParam(req).get("checkCode");
        String newpwd = getParam(req).get("password");

        String sendCode = (String) req.getSession().getAttribute("forgetCode");

        if (!checkCode.equals(sendCode)){
            req.setAttribute("msg","验证码错误！");
            req.getRequestDispatcher("/forget.jsp").forward(req,resp);
            return;
        }

        userService.updatePwdByEmail(email,newpwd);

        resp.sendRedirect("/index.jsp");
    }

    public void wx_login(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        Properties prop = new Properties();
        prop.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));

        String appid = prop.getProperty("wx.AppID");

        String redirect_uri = prop.getProperty("wx.redirect_uri");

        String url = "https://open.weixin.qq.com/connect/qrconnect?response_type=code"+
                "&appid=" + appid +
                "&redirect_uri=" + URLEncoder.encode(redirect_uri) +
                "&scope=snsapi_login";

        resp.sendRedirect(url);
    }
}
